#include "../common.h"
using namespace aigc;

extern __gnu_cxx ::hash_map<int, DECODER_HANDLE> _cmd_decoder(_CMD_END);

event_injection_handle(EVENT_SERIAL_MESSAGE, event_serial_message1,TaskCtx<String> *ctx) {
	CmdService::decodeAndDispense(ctx->ctx);
}

void CmdService::decodeAndDispense(const String &text) {
	if (text.length() >= 2 && text[0] == '{' && text[text.length() - 1] == '}') {
		CmdWrap cmdWrap;
		JsonHelper::JsonToObject(cmdWrap, text);
		if (cmdWrap.m < 0) {
			return;
		}
		dispense(CMD_KEY(cmdWrap.m), cmdWrap.body);
	}
}

void CmdService::registerHandle(CMD_KEY key, DECODER_HANDLE fun) {
	_cmd_decoder[key] = fun;
}
void CmdService::dispense(CMD_KEY key, const std::string &json) {
	if (json.empty()) {
		return;
	}
	if (_cmd_decoder.count(key) == 0) {
		return;
	}
	_cmd_decoder[key](json);
}

